<?php

namespace App\Http\Controllers;

use App\Models\Questionnaire;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Mockery\Exception;
use function PHPSTORM_META\map;

class QuestionnaireController extends WxBaseController
{

    public function index(){
        $user = $this->auth();
        $qa = Questionnaire::orderBy(DB::raw('RAND()'))->take(1)->first();
        $qa->status = $qa->isAnswered($user->id);
        $qa->coverimage = config('domain').'/'.$qa->coverimage;
        return $this->apiReturn(true,'success',$qa);
    }
    public function questions(){
        $id = Input::get('id');
        $questionnaire = Questionnaire::find($id);
        if($questionnaire){
            $list = $questionnaire->questions()->orderBy(DB::raw('RAND()'))->take(10)->get(['id','title','option']);
            return $this->apiReturn(true,'success',$list);
        }else{
            return $this->apiReturn(false,'error');
        }
    }
    public function answer(){
        $input = request();
        $questionnaire = Questionnaire::find($input->id);
        $correct = 0;
        foreach ($input->answer as $item){
            $question = $questionnaire->questions()->find($item['id']);
            $question&&array_equal(explode(',',$item['answer']),$question->answer)&&$correct++;
        }
        $fraction = round($correct/count($input->answer),2)*100;
        $score = get_score($fraction,$questionnaire->score);
        try{
            $questionnaire->wxusers()->attach($this->auth()->id);
            return $this->apiReturn(true,'success',['fraction'=>$fraction,'score'=>$score]);
        }catch (Exception $e){
            return $this->apiReturn(false,'error');
        }
    }
}